package tech.wetech.admin3.sys.service;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooAnotherMe;
import tech.wetech.admin3.sys.repository.AooAnotherMeRepository;
import tech.wetech.admin3.util.GetDateUtil;
import tech.wetech.admin3.util.HashUtil;
import tech.wetech.admin3.util.OrderUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class AooAnotherMeService {
  private final OssService ossService;
  private AooAnotherMeRepository anotherMeRepository;
  private AooPhoneCodeService phoneCodeService;
  private HashUtil hashUtil;
  private MsgCenterService msgCenterService;

  public AooAnotherMeService(
    OssService ossService,
    AooAnotherMeRepository anotherMeRepository,
    AooPhoneCodeService phoneCodeService,
    HashUtil hashUtil,
    MsgCenterService msgCenterService
  ) {
    this.ossService = ossService;
    this.anotherMeRepository = anotherMeRepository;
    this.phoneCodeService = phoneCodeService;
    this.hashUtil = hashUtil;
    this.msgCenterService = msgCenterService;
  }

  @Transactional
  public AooAnotherMe save(AooAnotherMe aooAnotherMe) {
    return anotherMeRepository.save(aooAnotherMe);
  }

//  public List<AooAnotherMe> getAllData() {
//    return anotherMeRepository.findAll();
//  }

  // 仅获取已支付的分身
  public List<AooAnotherMe> findByPaid(boolean paid) {
    return anotherMeRepository.findByPaid(paid);
  }

  public List<AooAnotherMe> getAllData() {
    return anotherMeRepository.findAll();
  }

  public AooAnotherMe findById(Integer id) {
    return anotherMeRepository.findById(id).orElse(null);
  }

  ;

  public List<AooAnotherMe> findByEmail(String email) {
    return anotherMeRepository.findByEmail(email);
  }

  public List<AooAnotherMe> findByStatus(Integer status) {
    return anotherMeRepository.findByStatus(status);
  }

  public List<AooAnotherMe> findByDigitalNameContaining(String digitalName) {
    return anotherMeRepository.findByDigitalNameContaining(digitalName);
  }



  @Transactional
  public boolean resetStatus(UUID uuid, Integer newStatus, String checkDesc) {
    AooAnotherMe aooAnotherMe = anotherMeRepository.findByUuid(uuid);
    if (aooAnotherMe != null) {
      // 检查新状态是否与旧状态相同
      if (aooAnotherMe.getStatus().equals(newStatus)) {
        // 如果状态相同，抛出一个RuntimeException或者自定义的异常
        throw new IllegalStateException("更新的状态与原状态相同，无需更新。");
      }

      aooAnotherMe.setStatus(newStatus);
      anotherMeRepository.save(aooAnotherMe);
      String name = aooAnotherMe.getDigitalName();
      String email = aooAnotherMe.getEmail();
      if (newStatus == 2) {
        // 审核通过的消息
        msgCenterService.createMessage("数字人身份创建成功", "您提交创建的自然人数字分身" + name + "数字身份已发放，您可在数字人身份创建页面点击“已拥有的认证”查看它的数字证书。", email);
      } else if (newStatus == 3) {
        // 审核驳回的消息
        msgCenterService.createMessage("数字人身份创建失败", "您提交创建的自然人数字分身" + name + "经审核驳回，审核意见为" + checkDesc + "；您可确认相关内容后，点击“数字人身份创建”重新提交申请。", email);
      }

      return true;
    } else {
      return false;
    }
  }

  @Transactional
  public AooAnotherMe createAnotherMe(
    String owner,
    String ownerIdNo,
    String email,
    String digitalName,
    String mobile,
    String vericode,
    String feature,
    String purpose,
    String career,
    String education,
    String microblog,
    MultipartFile[] modelFiles,
    MultipartFile[] images,
    String signFileUrl
  ) {
    if (images.length > 5) {
      throw new AooUserException("图片不能超过5张");
    }
    if (modelFiles != null && modelFiles.length > 5) {
      throw new AooUserException("模型文件不能超过5个");
    }

    List<String> imageUrls = new ArrayList<>();
    List<String> imageUrlHashes = new ArrayList<>();
    for (MultipartFile image : images) {
      if (image.getSize() > 10 * 1024 * 1024) {
        throw new AooUserException("图片不能大于10MB");
      }
      imageUrls.add(ossService.uploadImage(image));
      imageUrlHashes.add(hashUtil.getFileHash(image));
    }

    List<String> modelFileUrls = new ArrayList<>();
    List<String> modelFileHashes = new ArrayList<>();
    if (modelFiles != null) {
      for (MultipartFile modelFile : modelFiles) {
        if (modelFile.getSize() > 200 * 1024 * 1024) {
          throw new AooUserException("模型文件不能大于200MB");
        }
        modelFileUrls.add(ossService.uploadImage(modelFile));
        modelFileHashes.add(hashUtil.getFileHash(modelFile));
      }
    }

//    // 查重
//    List queryResult = anotherMeRepository.findByOwnerIdNoAndDigitalName(ownerIdNo, digitalName);
//    if (queryResult.size() > 0) {
//      throw new AooUserException("您已有该分身");  //  一个自然人禁止 同名分身
//    }

    boolean flag = phoneCodeService.verifyCode(mobile, vericode);
    if (!flag) {
      throw new AooUserException("验证码错误或已过期");
    }

    Gson gson = new Gson();
    AooAnotherMe aooAnotherMe = new AooAnotherMe();
    aooAnotherMe.setOwner(owner);
    aooAnotherMe.setOwnerIdNo(ownerIdNo);
    aooAnotherMe.setEmail(email);
    aooAnotherMe.setDigitalName(digitalName);
    aooAnotherMe.setMobile(mobile);
    aooAnotherMe.setFeature(feature);
    aooAnotherMe.setPurpose(purpose);
    aooAnotherMe.setCareer(career);
    aooAnotherMe.setEducation(education);
    aooAnotherMe.setMicroblog(microblog);
    aooAnotherMe.setCreateDate(GetDateUtil.getYyyyMMddHHmmss());
    aooAnotherMe.setSignFileUrl(signFileUrl);
    aooAnotherMe.setOutTradeNo(OrderUtil.generateOrderNumber("me"));
    aooAnotherMe.setImageUrls(gson.toJson(imageUrls));
    aooAnotherMe.setImageHashes(gson.toJson(imageUrlHashes));
    aooAnotherMe.setModelFileUrls(gson.toJson(modelFileUrls));
    aooAnotherMe.setModelFileHashes(gson.toJson(modelFileHashes));

    AooAnotherMe savedData = save(aooAnotherMe);
    if (savedData != null && savedData.getId() != null) { // 假设savedData有一个ID字段来确认持久化
      phoneCodeService.deleteCode(mobile);  //  操作后删除验证码，使失效
      System.out.println("保存虚拟人 AooAnotherMe---" + savedData);
      return savedData;
    } else {
      // 保存失败的情况
      throw new AooUserException("提交失败, 请重试");
    }
  }


  public AooAnotherMe findByUuid(UUID uuid) {
    return anotherMeRepository.findByUuid(uuid);
  }

  public boolean isImageHashExist(String hash) {
    var result = anotherMeRepository.findByImageHashesContaining(hash);
    System.out.println("anotherMe: " + result);
    return result != null && !result.isEmpty();
  }

  public boolean isModelFileHashExist(String hash) {
    var result = anotherMeRepository.findByModelFileHashesContaining(hash);
    System.out.println("anotherMe: " + result);
    return result != null && !result.isEmpty();
  }
}
